<template>
  <div>
    <!-- 头部标签 -->
    <van-nav-bar fixed>
      <template #left>
        <!-- <img class="logo" src="../../assets/toutiao_logo.png" alt="" /> -->
        <img class="logo" :src="imgObj"/>

      </template>
      <template #right>
        <van-icon  name="search" size="0.48rem" color="#fff" @click="$router.push('/search')"/>
      </template>
    </van-nav-bar>
      <!-- 频道部分 -->
      <!-- 加号编辑按钮 -->
       <van-icon name="plus" size="0.37333334rem" class="moreChannels" @click="show = true"/>
        <!-- 弹出层组件 -->
    <van-popup v-model="show" class="edit_wrap">
      <!-- 弹出层的主体区域 -->
      <channel-edit
      :userChannelList="channelList"
       @close="show = false"
       @add="addChannelFn"
       @delFn='delChannelFn'
      @changeChannel="channgeChannelFn"
       ></channel-edit>
    </van-popup>
      <van-tabs
       v-model="channelId"
        animated
        sticky
        offset-top="1.226667rem">

      <!-- 循环数组 -->
   <van-tab v-for="item in channelList" :key="item.id" :title="item.name" :name="item.id">

    <van-pull-refresh
    v-model="isLogin"
    @refresh="onRefresh"
    >
    <van-list
      v-model="loading"
      :finished="finished"
      :immediate-check='false'
      offset='50'
      finished-text="我是有底线的~~"
      @load="onLoad"
      >
    <!-- offset='50' 滚动条与底部距离小于 offset 时触发load事件 -->
    <!-- immediate-check  是否在初始化时立即执行滚动位置检查 -->
      <ArticleList :arr='articleItem' @del-art='del' ></ArticleList>
    </van-list>
    </van-pull-refresh>
  </van-tab>
</van-tabs>
  </div>
</template>

<script>

import logoPng from '@/assets/images/logo.png'
// updateUserchannelListAPI
import { getUserChannelListAPI, getArticlesListAPI } from '@/api/home'
import ArticleList from './ArticleList'
import ChannelEdit from './ChannelEdit.vue'
export default {
  name: 'Home',
  data () {
    return {
      imgObj: logoPng,
      // ...省略其他
      channelList: [], // 频道数据
      channelId: 0, // 默认显示频道id
      articleItem: [], // 接收请求过来的文章列表
      loading: false, // （控制上拉每一页的加载状态）是否处于加载状态，加载过程中不触发load事件
      finished: false, // （控制整个上拉的加载状态） 是否已加载完成，加载完成后不再触发load事件
      nextTime: undefined, // 默认pre_timestamp为控制
      isLogin: false, // 下拉加载停止
      show: false // 默认隐藏管理模块
    }
  },
  components: {
    ArticleList,
    ChannelEdit
  },
  // 监听改变的频道id
  watch: {
    // 监听频道id
    async channelId (newVal) {
      // 重置加载状态 不然的话切换频道不会加载
      this.loading = this.finished = false
      this.nextTime = null
      // 得到的是新的频道id
      // console.log(newVal)
      // console.log(this.channelId)
      // 监听到id切换后重新获取文章列表
      const resq = await getArticlesListAPI({
        channelId: this.channelId
      })
      // console.log(resq)
      const { results, pre_timestamp: timestamp } = resq.data.data
      // 请求到的文章列表 重新赋值给articleItem数组
      this.articleItem = results
      // 重新定义分页
      this.nextTime = timestamp
    }
  },
  async created () {
    const res = await getUserChannelListAPI()
    // console.log(res)
    // 请求的频道数组赋值给初始化的channelList
    this.channelList = res.data.data.channels
    // 传递实参 频道的id
    const resq = await getArticlesListAPI({
      channelId: this.channelId,
      timestamp: this.nextTime
    })
    // console.log(resq)
    // 请求到的文章列表 赋值给初始化articleItem数组
    const { results, pre_timestamp: timestamp } = resq.data.data
    // 请求到的文章列表 重新赋值给articleItem数组
    this.articleItem = results
    // 重新定义分页
    this.nextTime = timestamp
  },
  methods: {
    // 切换频道
    channgeChannelFn (obj) {
      this.channelId = obj // 传过来的频道ID, 影响tabs默认v-model的选择
      this.show = false
    },
    // 更新频道列表
    updateUserchannelList () {
      const arr = this.channelList.reduce((sum, obj, idx) => {
        const item = {
          id: obj.id,
          seq: idx + 1
        }
        if (obj.id !== 0) {
          sum.push(item)
        }
        return sum
      }, [])
      console.log(arr)
    },
    // 删除已选频道
    delChannelFn (i) {
      console.log(i)

      this.channelList.splice(i, 1)
      this.updateUserchannelList()
    },
    // 添加频道
    addChannelFn (obj) {
      this.channelList.push(obj)
      this.updateUserchannelList()
    },
    // 不感兴趣删除文章
    async del (i) {
      this.articleItem.splice(i, 1)
      if (this.articleItem.length < 6) {
        const resq = await getArticlesListAPI({
          channelId: this.channelId,
          timestamp: this.nextTime
        })
        const { results, pre_timestamp: timestamp } = resq.data.data
        if (timestamp === null || results.length > 10) {
          return
        }
        this.nextTime = timestamp
        // 请求到的文章列表 赋值给初始化articleItem数组
        this.articleItem = [...this.articleItem, ...results]
      }
    },
    // 上拉加载
    async onLoad () {
    // console.log('加载开始')
    // 传递实参 频道的id
      const resq = await getArticlesListAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      // console.log(resq)

      const { results, pre_timestamp: timestamp } = resq.data.data
      if (timestamp === null || results.length > 10) {
        this.finished = true
        return
      }
      this.nextTime = timestamp
      // 请求到的文章列表 赋值给初始化articleItem数组
      this.articleItem = [...this.articleItem, ...results]
      this.loading = false
    // console.log('加载结束')
    },
    // 下拉加载
    async onRefresh () {
    // 传递实参 频道的id
      const resq = await getArticlesListAPI({
        channelId: this.channelId,
        timestamp: this.nextTime
      })
      // console.log(resq)

      const { results, pre_timestamp: timestamp } = resq.data.data
      if (timestamp === null || results.length < 10) {
      // this.$toast('没有更多资源~~')
        this.isLogin = false
        return
      }
      this.nextTime = timestamp
      // 请求到的文章列表 赋值给初始化articleItem数组
      // 直接替换数组
      // this.articleItem = results
      // 延迟一秒后用户体验更佳
      setTimeout(() => {
      // 保存原有的数组
        this.articleItem = [...results, ...this.articleItem]
        this.isLogin = false
      }, 1000)
    // console.log('加载结束')
    }
  }
}
</script>

<style scoped lang="less">
.logo {
  width: 100px;
  height: 30px;
}
/* tab内容距离tab导航的距离 */
/deep/ .van-tabs__content{
  padding-top: 44px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 20px;
  background-color: #fff;
}
// 设置小图标的样式
.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 999;
}
/* 频道编辑弹出层铺满屏幕 */
.edit_wrap{
  width: 100%;
  height: 100%;
}
</style>
